package renguanyu.app.tools.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

public class HtmlToJsController {

	@FXML
	TextField variable;
	@FXML
	TextArea sourceHtml;
	@FXML
	TextArea targetJs;
	@FXML
	TextArea sourceJs;
	@FXML
	TextArea targetHtml;

	@FXML
	public void htmlToJs() {
		String textArea1Text = sourceHtml.getText();
		String[] rowArray = textArea1Text.split("\n");
		List<String> result = new ArrayList<>();
		String tempVar = "html";
		if (!variable.getText().isEmpty()) {
			String text = variable.getText();
			tempVar = text;
		}
		result.add("var " + tempVar + "='';");
		for (int i = 0; i < rowArray.length; i++) {
			String row = rowArray[i];
			result.add("" + tempVar + "+='" + row + "';");

		}
		targetJs.clear();
		for (int i = 0; i < result.size(); i++) {
			String newStr = result.get(i);
			targetJs.appendText(newStr);
			targetJs.appendText("\n");
		}
	}

	@FXML
	public void jsToHtml() {
		String REGEX = "\\+\\='(.*?)';";
		List<String> result = new ArrayList<>();
		String jsStr = sourceJs.getText();
		if (!variable.getText().isEmpty()) {
			String text = variable.getText();
			REGEX = text + REGEX;
		}
		Pattern p = Pattern.compile(REGEX);
		String[] rowArray = jsStr.split("\n");
		for (int i = 0; i < rowArray.length; i++) {
			String row = rowArray[i];
			Matcher m = p.matcher(row);
			while (m.find()) {
				String content = m.group(1);
				result.add(content);
			}
		}
		targetHtml.clear();
		for (int i = 0; i < result.size(); i++) {
			String newStr = result.get(i);
			targetHtml.appendText(newStr);
			targetHtml.appendText("\n");
		}
	}

}
